<template>
    <div class="agent-management">
        <div class="header-actions">
            <el-button type="primary" @click="handleAdd" :icon="Plus">新增经济人</el-button>
        </div>
        <el-table
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName">
          <el-table-column
            prop="name"
            label="姓名">
          </el-table-column>
          <el-table-column label="负责艺人">
            <template #default="scope">
              <div v-if="scope.row.artistNames && scope.row.artistNames.length">
                <span v-for="(name, index) in scope.row.artistNames" :key="index" class="artist-tag">
                  {{ name }}
                </span>
              </div>
              <span v-else>未指派艺人</span>
            </template>
          </el-table-column>
          <el-table-column prop="baseCity" label="驻地">
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
              <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增经济人对话框 -->
        <el-dialog 
          v-model="addDialogVisible" 
          title="新增经济人" 
          width="45%" 
          destroy-on-close
          top="5vh"
          class="agent-dialog">
          <div class="dialog-header-divider"></div>
          <div class="form-container">
            <el-form 
              :model="agentForm" 
              :rules="rules" 
              ref="agentFormRef" 
              label-width="110px" 
              class="agent-form"
              label-position="left">
              <el-form-item label="经纪人名称" prop="name">
                <el-input 
                  v-model="agentForm.name" 
                  placeholder="请输入经纪人名称"
                  prefix-icon="User">
                </el-input>
              </el-form-item>
              
              <el-form-item label="驻地" prop="baseCity">
                <el-autocomplete
                  v-model="agentForm.baseCity"
                  :fetch-suggestions="queryAddressSearch"
                  placeholder="请输入或选择驻地"
                  style="width: 100%"
                  prefix-icon="Location"
                ></el-autocomplete>
              </el-form-item>

              <el-form-item label="负责艺人">
                <el-table :data="allArtists" stripe style="width: 100%; margin-top: 10px;">
                  <el-table-column prop="name" label="艺人姓名"></el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="scope">
                      <el-button 
                        v-if="agentForm.artistNames.includes(scope.row.name)"
                        type="danger" 
                        size="small"
                        @click="removeArtistFromAgent(scope.row.name)">
                        删除
                      </el-button>
                      <el-button 
                        v-else
                        type="primary" 
                        size="small"
                        @click="addArtistToAgent(scope.row.name)">
                        添加
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="addDialogVisible = false" :icon="Close">取消</el-button>
              <el-button type="primary" @click="submitAgentForm('agentFormRef')" :icon="Check">确认</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 修改艺人对话框 -->
        <el-dialog 
          v-model="editDialogVisible" 
          title="修改艺人信息" 
          width="45%" 
          destroy-on-close
          top="5vh"
          class="agent-dialog">
          <div class="dialog-header-divider"></div>
          <div class="form-container">
            <el-form 
              :model="agentForm" 
              :rules="rules" 
              ref="editFormRef" 
              label-width="110px" 
              class="agent-form"
              label-position="left">
              <el-form-item label="经纪人名称" prop="name">
                <el-input 
                  v-model="agentForm.name" 
                  placeholder="请输入经纪人名称"
                  prefix-icon="User">
                </el-input>
              </el-form-item>
              
              <el-form-item label="驻地" prop="baseCity">
                <el-autocomplete
                  v-model="agentForm.baseCity"
                  :fetch-suggestions="queryAddressSearch"
                  placeholder="请输入或选择驻地"
                  style="width: 100%"
                  prefix-icon="Location"
                ></el-autocomplete>
              </el-form-item>

              <el-form-item label="负责艺人">
                <el-table :data="allArtists" stripe style="width: 100%; margin-top: 10px;">
                  <el-table-column prop="name" label="艺人姓名"></el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="scope">
                      <el-button 
                        v-if="agentForm.artistNames.includes(scope.row.name)"
                        type="danger" 
                        size="small"
                        @click="removeArtistFromAgent(scope.row.name)">
                        删除
                      </el-button>
                      <el-button 
                        v-else
                        type="primary" 
                        size="small"
                        @click="addArtistToAgent(scope.row.name)">
                        添加
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="editDialogVisible = false" :icon="Close">取消</el-button>
              <el-button type="primary" @click="updateAgent('editFormRef')" :icon="Check">确认</el-button>
            </div>
          </template>
        </el-dialog>
    </div>
</template>
  
<style>
.artist-tag {
    display: inline-block;
    padding: 4px 8px;
    margin: 2px;
    background-color: #ecf5ff;
    border: 1px solid #d9ecff;
    border-radius: 4px;
    color: #409eff;
    font-size: 12px;
  }

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  
  .el-table .danger-row {
    background: #fef0f0;
  }
  
  .el-table .special-row {
    background: #e6f1ff;
  }

  .agent-management {
    padding: 20px;
  }

  .header-actions {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .agent-form .el-form-item__label {
    font-weight: bold;
    color: #303133;
  }

  .agent-form .el-input-number {
    width: 100%;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 10px;
  }
  
  .agent-dialog .el-dialog__header {
    margin-right: 0;
    text-align: center;
    padding: 15px 20px 5px;
  }
  
  .agent-dialog .el-dialog__body {
    padding: 0px 20px 20px;
  }
  
  .agent-dialog .el-dialog__title {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .dialog-header-divider {
    height: 1px;
    background-color: #EBEEF5;
    margin-bottom: 15px;
  }
  
  .agent-form .el-input__inner,
  .agent-form .el-select .el-input__inner,
  .agent-form .el-autocomplete .el-input__inner {
    border-radius: 4px;
    height: 36px;
  }

  .agent-form .el-form-item {
    margin-bottom: 16px;
  }
  
  .form-container {
    max-width: 500px;
    margin: 0 auto;
  }
</style>
  
<script>
  import request from '@/utils/request'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { 
    Plus, Edit, Delete, 
    User, Flag, Star, 
    TrendCharts, Money, Calendar, 
    Location, Close, Check 
  } from '@element-plus/icons-vue'
  
  export default { 
    methods: {
      tableRowClassName({row}) {
        // 正常情况
        return '';
      },

      getAgentInfo() {
        request.get('/getAgentInfo').then(res => {
          if(res.data.code === 200){
            this.tableData = res.data.data;
          } else {
            ElMessage.error('获取经纪人信息失败')
          }
        }).catch(err => {
          console.error('获取经纪人信息失败:', err)
          ElMessage.error('获取经济人信息失败')
        })
      },

      // 打开新增经纪人对话框
      handleAdd() {
        this.agentForm = {
          name: '',
          artistNames: [], 
          baseCity: ''
        }
        this.addDialogVisible = true
        // 重置表单校验状态
        if (this.$refs.agentFormRef) {
          this.$refs.agentFormRef.resetFields()
        }
        this.getAllArtists();
      },

      // 提交新增经纪人表单
      submitAgentForm(formRef) {
        // 表单校验
        this.$refs[formRef].validate(valid => {
          if (!valid) {
            ElMessage.warning('请完善表单信息')
            return
          }
          
          // 检查艺人名称是否已存在
          const isAgentExists = this.tableData.some(agent => agent.name === this.agentForm.name)
          if (isAgentExists) {
            ElMessage.warning(`经纪人"${this.agentForm.name}"已存在，不能重复添加`)
            return
          }

          request.post('/addAgent', this.agentForm).then(res => {
            if (res.data.code === 200) {
              // 添加成功，刷新数据
              ElMessage.success(res.data.msg || '添加经纪人成功')
              this.getAgentInfo()
              // 关闭对话框
              this.addDialogVisible = false
            } else {
              ElMessage.error(res.data.msg || '添加经纪人失败')
            }
          }).catch(err => {
            console.error('添加经纪人失败:', err)
            ElMessage.error('添加经纪人失败')
          })
        })
      },

      // 打开修改经纪人对话框
      handleEdit(row) {
       // 获取经纪人详细信息（包含关联艺人）
        request.get(`/getAgentWithArtists/${row.id}`).then(res=>{
          if (res.data.code === 200) {
          this.agentForm = {
            id: row.id,
            name: res.data.data.name,
            baseCity: res.data.data.baseCity,
            artistNames: res.data.data.artistNames
          };
          this.editingAgentId = row.id;
          this.editDialogVisible = true;
        } else {
          ElMessage.error('获取经纪人详情失败');
        }
        });
        this.getAllArtists();
      },

      // 更新经济人信息
      updateAgent(formRef) {
        // 表单校验
        this.$refs[formRef].validate(valid => {
          if (!valid) {
            ElMessage.warning('请完善表单信息')
            return
          }

          // 检查艺人名称是否已存在
          const isAgentExists = this.tableData.some(
          agent => agent.name === this.agentForm.name && agent.id !== this.editingAgentId
          )
          if (isAgentExists) {
            ElMessage.warning(`经济人"${this.agentForm.name}"已存在，请更换名称`)
            return
          }
        
          request.put(`/updateAgent/${this.editingAgentId}`, this.agentForm).then(res => {
            if (res.data.code === 200) {
              // 更新成功，刷新数据
              ElMessage.success(res.data.msg || '修改经济人成功')
              this.getAgentInfo()
              // 关闭对话框
              this.editDialogVisible = false
            } else {
              ElMessage.error(res.data.msg || '修改经济人失败')
            }
          }).catch(err => {
            console.error('更新经济人失败:', err)
            ElMessage.error('更新经济人失败')
          })
        })
      },

      // 删除经济人
      handleDelete(row) {
        ElMessageBox.confirm(
          `确定要删除"${row.name}"的记录吗？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          // 用户确认删除
          request.delete(`/deleteAgent/${row.id}`).then(res => {
            if (res.data.code === 200) {
              // 删除成功，刷新数据
              ElMessage.success(res.data.msg || '删除经济人成功')
              this.getAgentInfo()
            } else {
              ElMessage.error(res.data.msg || '删除经济人失败')
            }
          }).catch(err => {
            console.error('删除经济人失败:', err)
            ElMessage.error('删除经济人失败')
          })
        }).catch(() => {
          // 用户取消删除
          ElMessage.info('已取消删除')
        })
      },

      //获取所有的艺人
      getAllArtists(){
        return new Promise((resolve, reject) => {
          if (this.artistList && this.artistList.length) {
            resolve(this.artistList);
          } else {
            request.get('/getArtistInfo').then(res => {
              if (res.data.code === 200) {
                this.allArtists = res.data.data;
                resolve(res.data.data);
              } else {
                reject('获取艺人信息失败');
              }
            }).catch(err => {
              console.error('获取艺人信息失败:', err);
              reject(err);
            });
          }
        });
      },

      // 驻地搜索建议
      queryAddressSearch(queryString, cb) {
        const addressList = [
          '北京', '上海', '广州', '深圳', '杭州',
          '南京', '成都', '重庆', '武汉', '西安',
          '长沙', '贵阳', '哈尔滨', '台北', '香港',
          '新加坡', '东京', '首尔', '纽约', '洛杉矶'
        ]
        
        const results = queryString
          ? addressList.filter(item => item.includes(queryString))
          : addressList
          
        // 格式化为组件需要的数据结构
        const suggestions = results.map(item => {
          return { value: item }
        })
        
        cb(suggestions)
      },

      /**
       * Assign section begin
       */
      // 添加艺人到当前经纪人
      addArtistToAgent(artistId) {
        if (!this.agentForm.artistNames.includes(artistId)) {
          this.agentForm.artistNames.push(artistId);
        }
      },

      // 从当前经纪人移除艺人
      removeArtistFromAgent(artistId) {
        const index = this.agentForm.artistNames.indexOf(artistId);
        if (index !== -1) {
          this.agentForm.artistNames.splice(index, 1);
        }
      },
      /**
       * Assign section end
       */
    },
    created() {
      this.getAgentInfo()
    },
    data() {
      return {
        tableData: [],
        addDialogVisible: false,
        editDialogVisible: false,
        editingArtistId: null,
        agentForm: {
          name: '',
          artistNames: [], // 存储艺人ID数组
          baseCity: ''
        },

        allArtists:[],
        
        // 表单验证规则
        rules: {
          name: [
            { required: true, message: '请输入经济人名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ],
          remaining: [
            { required: true, message: '请输入距离续期天数', trigger: 'blur' },
            { type: 'number', message: '天数必须为数字值', trigger: 'blur' }
          ],
          baseCity: [
            { required: true, message: '请输入或选择驻地', trigger: 'blur' }
          ]
        },

        Plus,
        Edit,
        Delete,
        User,
        Flag,
        Star,
        TrendCharts,
        Money,
        Calendar,
        Location,
        Close,
        Check
      }
    }
  }
</script>
  